<?php
namespace App\Api\Controllers\Zgyd;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BaseController
{
    static $config, $instance, $data, $sign;

    const SCAN_URL ='https://www.yadapayment.com:10001/merfpay';

    const QR_URL = 'https://www.yadapayment.com:10001/bjyada/ydpayment';


    public static function getInstance ()
    {
        if (! isset(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function params ($body)
    {

        $prams = [
            "MsgVer" => "1000",
            "InDate" => date('Ymd'),
            "InTime" => date('His'),
            "MerTp" => "01",
            "Drctn" => "11",
        ];
        $priKey = $body['priKey'];
        $signParams = $body['SignParams'];
        unset($body['priKey']);
        unset($body['SignParams']);
        $data = array_merge($prams, $body);
        $data = array_merge($data, $signParams);


        self::$data = $data;
        self::$data['Sign'] = $this->sign($signParams, $priKey);
        return $this;
    }

    /**
     * 加签
     * @param string $data
     */
    private function sign($data, $privateKey)
    {
        $str = $this->getSignContent($data);
        Log::channel("zgyd")->info("str", [$str]);
        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($privateKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        openssl_sign($str, $signature, $privateKey, OPENSSL_ALGO_SHA256);
        return base64_encode($signature);
    }


    /**
     * ASCII排序
     * @param array $params
     * @param $key
     * @return bool|string
     */
    public function getSignContent ($params)
    {
        return implode('|', $params);
    }

    public function verify ($data, $header)
    {

        if (isset($data['merTradeNo']) && !empty($data['merTradeNo'])) {
            $merchant = DB::table("zgyd_stores")->where('mch_id', $data['oldTermId'])->first();
            $sign = md5(json_encode($data).'&'.$merchant->key);
            if ($sign == $header['sign'] && $data['respCode'] == '00') {
                return true;
            }
        }

        if (isset($data['merTradeNo']) && !empty($data['merTradeNo'])) {
            $merchant = DB::table("zgyd_stores")->where('mch_id', $data['oldTermId'])->first();
            $payData = [
                "mch_id" => $merchant->mch_id,
                "pos_no" => $merchant->pos_no,
                "key" => $merchant->key,
                "out_trade_no" =>$data['merTradeNo']
            ];

            $return = (new PayController())->order_query($payData);
            if ($return['status'] == 1) {
                return true;
            }
        }
        return false;
    }




    public function build ($fun, $url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url); //设置选项，包括URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(self::$data));


        $headers = array(
            "Content-Type: application/json",
            "Charset: UTF-8"
        );

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $output = curl_exec($ch); //执行并获取HTML文档内容

        curl_close($ch); //释放curl句柄


        Log::channel("zgyd")->info($fun."_Request", [$url, self::$data]);

//        $output = $this->returnJson($output);
        $result = mb_convert_encoding($output, 'utf-8', 'GB2312');
        $output = json_decode($result, true);

        Log::channel("zgyd")->info($fun."_Response", $output);
        return $output;

    }


    public function returnJson ($gb2312Json)
    {
        // 步骤1：转换为UTF-8
        $utf8Json = mb_convert_encoding($gb2312Json, 'UTF-8', 'GBK');

        // 步骤2：解析JSON
        $array = json_decode($utf8Json, true);

        foreach ($array as $key => $value) {
            $array[$key] = mb_convert_encoding($value, 'GBK', 'UTF-8');
        }
        return $array;
    }

}